<?php
namespace App\Service;

use App\Models\Customer\Customer; //会员表

use App\Models\Customer\CustRank; //会员等级表

use App\Models\Promotion\PromotionMaster; //商品促销表

use App\Models\Promotion\PromotionOrder; //订单促销表

use App\Models\Bill\BillUsePromotion; //商品促销会员购买记录表

use App\Models\Bill\Bill; //订单表

use App\Models\Goods\GoodsSaleEdit; //商品促销会员购买记录表

use App\Models\Card\CardCoupon; //卡券表

use App\Models\ConfigureFunction; //功能配置表

class PromotionService
{

    /**
     * 商品促销
     * @param $arg_array
     * @return array
     */
    public static function goods( $arg_array )
    {

        //商品网购号
        if (!isset($arg_array['postID']) || !ebsig_is_int($arg_array['postID'])) {
            $arg_array['postID'] = 0;
        }

        //商品售价
        if (!isset($arg_array['salePrice']) || empty($arg_array['salePrice'])) {
            $arg_array['salePrice'] = 0;
        }

        //商品数量
        if (!isset($arg_array['goods_amount']) || !ebsig_is_int($arg_array['goods_amount'])) {
            $arg_array['goods_amount'] = 1;
        }

        //门店ID
        if (!isset($arg_array['mallID']) || ebsig_is_int($arg_array['mallID'])) {
            $arg_array['mallID'] = 0;
        }

        //区域ID
        if (!isset($arg_array['mallareaID']) || ebsig_is_int($arg_array['mallareaID'])) {
            $arg_array['mallareaID'] = 0;
        }

        //会员号
        if (!isset($arg_array['pcustID']) || !ebsig_is_int($arg_array['pcustID'])) {
            $arg_array['pcustID'] = 0;
        }

        //是否开启严格结算
        if (!isset($arg_array['check']) || !ebsig_is_int($arg_array['check'])) {
            $arg_array['check'] = 0;
        }

        $real_sale_price = $arg_array['salePrice']; //实售价
        $real_salePoints = $arg_array['salePoints']; //实赠送积分

        $domain_url = ConfigureFunction::getConfigureField(43, 'domain_url');

        /**
         * 查询会员等级信息
         */
        $rankID = 0;

        //查询会员信息
        $customer  = Customer::select('rankID')->where('pcustID', $arg_array['pcustID'])->first();
        if ( $customer ) {
            //查询会员等级信息
            $rank_data = CustRank::select('rankID')->where('rankID', $customer['rankID'])->first();
            if ( $rank_data ) {
                $rankID = $rank_data['rankID'];
            }
        }

        //会员促销价格
        if (isset($arg_array['cust_promotion']) && $arg_array['cust_promotion'] == 1) {

//            $cust_p_array = self::calculate_rank(array(
//                'rate' => $rank_data['rate'],
//                'discount_flg' => $rank_data['discount_flg'],
//                'pointsRate' => $rank_data['pointsRate'],
//                'api_customer_rank' => $rank_data['api_customer_rank'],
//                'salePrice' => $arg_array['salePrice'],
//                'marketPrice' => $arg_array['marketPrice'],
//                'salePoints' => $arg_array['salePoints'],
//                'product_code' => $arg_array['product_code']
//            ));
//
//            $real_sale_price = $cust_p_array['price'];
//            $real_salePoints = $cust_p_array['salePoints'];

        }

        $return_data = array(
            'price' => $real_sale_price,
            'salePoints' => $real_salePoints,
            'gift' => null,
            'promotion' => array()
        );

        //查询促销活动
        $now = date('Y-m-d H:i:s');
        $where = [
            [ 'start_time' , '<=' , $now],
            [ 'end_time' , '>=' , $now],
            [ 'useFlg' , '=' , 1]
        ];
        $goodsPromotion = PromotionMaster::where($where)->orderBy('priority', 'desc')->get();
        if ( !$goodsPromotion ) {
            return $return_data;
        }
        $goodsPromotion = $goodsPromotion->toArray();

        $promotion_type_key_array = array();
        foreach ( $goodsPromotion as $promotion ) {

            //促销扩展数据
            $promotion_json = json_decode($promotion['promotion_json'], true);

            //检查商品筛选
            if (isset($promotion_json['selector_type']) && $promotion_json['selector_type'] == 2) {
                if ($promotion_json['selector_relation'] && !in_array($arg_array['postID'], $promotion_json['select_goods']))
                    continue;
                if (!$promotion_json['selector_relation'] && in_array($arg_array['postID'], $promotion_json['select_goods'])) {
                    continue;
                }
            }

            //检查会员等级
            if (isset($promotion_json['cust_rank']) && !in_array($rankID, $promotion_json['cust_rank']))
                continue;

            //筛选大区
            if (isset($promotion_json['mallareaID']) && $arg_array['mallareaID'] != $promotion_json['mallareaID'])
                continue;

            //筛选平台
            if (isset($arg_array['platform'], $promotion_json['platform']) && !in_array($arg_array['platform'], $promotion_json['platform']))
                continue;

            //筛选门店
            if (isset($promotion_json['mall_support_type']) && $promotion_json['mall_support_type'] == 2) {
                $is_has = 0;
                foreach($promotion_json['mall'] as $mall){
                    if ($mall['mallID'] == $arg_array['mallID'] && $is_has == 0)
                        $is_has = 1;
                }
                if ($is_has == 0)
                    continue;
            }

            if ( isset($promotion_type_key_array[$promotion['promotion_type']]) ) {
                continue;
            }

            $p_data = array(
                'promotion_id' => $promotion['promotion_id'],
                'remark' => $promotion['promotion_name'],
                'promotion_type' => $promotion['promotion_type'],
                'start_time' => $promotion['start_time'],
                'end_time' => $promotion['end_time'],
                'gift' => null,
                'selected' => 0,
                'half_money' => 0,
                'goods_amount' => $arg_array['goods_amount']
            );

            if ( $promotion['promotion_type'] == 1 ) {//商品特价
                if (!empty($promotion_json['limit_num'])) {
                    if ($promotion_json['limit_num'] < $arg_array['goods_amount'])
                        $p_data['goods_amount'] = $promotion_json['limit_num'];
                    if ($arg_array['check']) {
                        $promotion_use_data = BillUsePromotion::where(['promotion_id'=>$promotion['promotion_id'],'pcustID'=>$arg_array['pcustID']])->count();
                        if ( $promotion_use_data > 0 && ($promotion_use_data + $p_data['goods_amount'] > $promotion_json['limit_num'])) {
                            continue;
                        }
                    }
                }
                $p_data['limit_num'] = $promotion_json['limit_num'];
                $real_sale_price = $promotion_json['special_money'];

            } else if ( $promotion['promotion_type'] == 2 ) {//商品赠品
                if ( $arg_array['goods_amount'] < $promotion_json['buy_num'] && $arg_array['check'] ) {
                    continue;
                }
                if ( empty($promotion_json['gift_goods']) ) {
                    continue;
                }
                $multiple = floor($arg_array['goods_amount']/$promotion_json['buy_num']);
                $multiple = $multiple <= 0 ? 1 : $multiple;
                foreach($promotion_json['gift_goods'] as $gift){
                    $goods_array = GoodsSaleEdit::where(['postID' => $gift['postID']])->first();
                    if ( !$goods_array ) {
                        continue;
                    }
                    $goods_array = $goods_array->toArray();
                    $goods_array['saleAmount'] = $gift['saleAmount'] * $multiple;
                    $goods_array['img_url'] = $domain_url . $goods_array['goodsMainPic'];
                    $p_data['gift'][] = $goods_array;
                }
                $p_data['buy_num'] = $promotion_json['buy_num'];
            } else if ( $promotion['promotion_type'] == 3 ) {//商品折扣
                $p_data['discount'] = $promotion_json['discount'];
                $real_sale_price = round($arg_array['salePrice'] * $promotion_json['discount'], 2);
            } else if ( $promotion['promotion_type'] == 4 ) {
                if ( $arg_array['goods_amount'] < 2 ) {
                    continue;
                }
                $half_amount = floor($arg_array['goods_amount']/2);
                $p_data['half_money'] = round($real_sale_price * (1 - $promotion_json['discount']), 2) * $half_amount;
                $p_data['discount'] = $promotion_json['discount'];
                $real_sale_price = round(($real_sale_price * $arg_array['goods_amount'] - $p_data['half_money'])/$arg_array['goods_amount'], 2);
            }

            $promotion_type_key_array[$promotion['promotion_type']] = 1;

            if (empty($return_data['promotion'])) {
                $p_data['selected'] = 1;
                $return_data['price'] = $real_sale_price;
                $return_data['salePoints'] = $real_salePoints;
                $return_data['gift'] = $p_data['gift'];
            }

            $return_data['promotion'][] = $p_data;

        }

        return $return_data;

    }


    /**
     * 订单促销
     * @param $arg_array
     * @param $orders_goods_array
     * @return array
     */
    public static function orders( $arg_array, $orders_goods_array ) {

        //区域ID
        if (!isset($arg_array['mallareaID']) || !ebsig_is_int($arg_array['mallareaID'])) {
            $arg_array['mallareaID'] = 0;
        }

        //门店ID
        if (!isset($arg_array['mallID']) || !ebsig_is_int($arg_array['mallID'])) {
            $arg_array['mallID'] = 0;
        }

        //是否使用优惠券
        if (!isset($arg_array['is_use_coupon']) || !ebsig_is_int($arg_array['is_use_coupon'])) {
            $arg_array['is_use_coupon'] = 0;
        }

        //平台
        if (!isset($arg_array['platform']) || !ebsig_is_int($arg_array['platform'])) {
            $arg_array['platform'] = 0;
        }

        //会员号
        if (!isset($arg_array['pcustID']) || !ebsig_is_int($arg_array['pcustID'])) {
            $arg_array['pcustID'] = 0;
        }

        $domain_url = ConfigureFunction::getConfigureField(43, 'domain_url');

        /**
         * 查询会员等级信息
         */
        $rankID = 0;

        //查询会员信息
        $customer  = Customer::select('rankID')->where('pcustID', $arg_array['pcustID'])->first();
        if ( $customer ) {
            //查询会员等级信息
            $rank_data = CustRank::select('rankID')->where('rankID', $customer['rankID'])->first();
            if ( $rank_data ) {
                $rankID = $rank_data['rankID'];
            }
        }

        //查询促销活动
        $now = date('Y-m-d H:i:s');
        $where = [
            [ 'start_time' , '<=' , $now],
            [ 'end_time' , '>=' , $now],
            [ 'useFlg' , '=' , 1]
        ];
        $orderPromotion = PromotionOrder::where($where)->orderBy('priority', 'desc')->get();
        if ( !$orderPromotion ) {
            return null;
        }

        $selected_array = array();
        $return_data = array();
        $meet_array = array();

        foreach($orderPromotion as $promotion) {

            //促销扩展数据
            $promotion_json = json_decode($promotion['promotion_json'], true);

            //筛选大区
            if (isset($promotion_json['mallareaID']) && $arg_array['mallareaID'] != $promotion_json['mallareaID']) {
                continue;
            }

            //筛选门店
            if (isset($promotion_json['mall_support_type']) && $promotion_json['mall_support_type'] == 2) {
                $is_has = 0;
                if (isset($promotion_json['mall'])) {
                    foreach($promotion_json['mall'] as $mall){
                        if ($mall['mallID'] == $arg_array['mallID'] && $is_has == 0)
                            $is_has = 1;
                    }
                }
                if ($is_has == 0)
                    continue;
            }

            //筛选平台
            if (isset($promotion_json['platform']) && !in_array($arg_array['platform'], $promotion_json['platform'])) {
                continue;
            }
            
            //检查是否使用优惠券
            if ($promotion_json['is_use_coupon'] != 2 && $promotion_json['is_use_coupon'] != $arg_array['is_use_coupon']) {
                continue;
            }

            //检查是否首单
            if ($promotion_json['is_first_order']) {
                $bill_data = Bill::where(['pcustID'=>$arg_array['pcustID'], 'billChannel'=>$arg_array['platform']])->whereNotIn('bill_status', [5,6])->count();
                if ( $bill_data > 0 )
                    continue;
            }

            //检查会员等级
            if ( isset($promotion_json['cust_rank']) && !in_array($rankID, $promotion_json['cust_rank']) ) {
                continue;
            }

            $total_money = 0;
            $goods_amount = 0;
            $merge = array();

            //促销重组方式： 1、全部商品 2、部分并排斥商品 3、部分并包含商品
            if ($promotion_json['selector_type'] == 2) {
                if ($promotion_json['selector_relation'] == 1) {
                    $goods_selector_type = 3;
                } else {
                    $goods_selector_type = 2;
                }
            } else {
                $goods_selector_type = 1;
            }

            foreach($orders_goods_array as $key=>$goods) {

                if (in_array($goods_selector_type, array(2, 3))) {
                    if ((isset($goods['type']) && $goods['type'] == 'group') || in_array($goods['postID'], $selected_array))
                        continue;

                    if ($goods_selector_type == 2) {
                        if (!empty($promotion_json['select_goods']) && in_array($goods['postID'],$promotion_json['select_goods']))
                            continue;

                    } else {
                        if (!in_array($goods['postID'],$promotion_json['select_goods']))
                            continue;

                    }
                    $merge[$goods['postID']] = $goods['postID'];
                    $selected_array[$goods['postID']] = $goods['postID'];

                }

                $price = 0;
                if (isset($goods['price'])) {
                  $price = $goods['price'];
                }
                $total_money += $price * $goods['goods_amount'];
                $goods_amount += $goods['goods_amount'];

            }

            //没有符合订单促销的商品
            if ($goods_amount == 0) {
                continue;
            }

            //赠品、加价换购商品、赠送卡券、重复倍数
            $g = null; $e = null; $coupon_array = null; $multiple = 1;

            //检查订单限制条件（限额/限件）
            if ($promotion_json['condition'] == 1) {
                $condition = $total_money;
            } else {
                $condition = $goods_amount;
                $promotion_json['condition_content'] = intval($promotion_json['condition_content']);
            }

            //检查是否累计
            if ( !empty($promotion_json['is_repeat']) && $promotion_json['is_repeat'] == 1 ) {
                $multiple = floor($condition/$promotion_json['condition_content']);
            }

            //赠品
            if ($promotion['promotion_type'] == 3) {
                foreach($promotion_json['gift_goods'] as $goods) {
                    $result_array = GoodsSaleEdit::where(['postID'=>$goods['postID']])->first();
                    if ( !$result_array ) {
                        continue;
                    }
                    $result_array = $result_array->toArray();
                    $g[$goods['postID']] = array(
                        'goodsName' => $result_array[0]['goodsName'],
                        'saleAmount' => $goods['saleAmount'] * $multiple,
                        'postID' => $goods['postID'],
                        'goodsID' => $result_array[0]['goodsID'],
                        'salePrice' => $result_array[0]['salePrice'],
                        'marketPrice' => $result_array[0]['marketPrice'],
                        'price' => $result_array[0]['salePrice'],
                        'mainPostID' => $result_array[0]['mainPostID'],
                        'product_code' => $result_array[0]['product_code'],
                        'spec' => $result_array[0]['spec'],
                        'img_link' => $domain_url . $result_array[0]['goodsMainPic'],
                        'link' => set_goods_link($goods['postID']),
                        'wap_link' => set_wap_goods_link($goods['postID']),
                        'promotionID' => $promotion['promotion_id']
                    );
                }
            }

            //加钱换购商品
            if ($promotion['promotion_type'] == 7) {
                $temp_data = array();
                foreach ($promotion_json['gift_goods'] as $exchange) {
                    $temp_data[] = $exchange['exchange_price'];
                }
                array_multisort($temp_data,SORT_ASC, $promotion_json['gift_goods']);
                foreach($promotion_json['gift_goods'] as $goods) {
                    $result_array = GoodsSaleEdit::where(['postID'=>$goods['postID']])->first();
                    if ( !$result_array ) {
                        continue;
                    }
                    $result_array = $result_array->toArray();
                    $e[$goods['postID']] = array (
                        'goodsName' => $result_array[0]['goodsName'],
                        'saleAmount' => $goods['saleAmount'],
                        'postID' => $goods['postID'],
                        'goodsType' => $result_array[0]['goodsType'],
                        'goodsID' => $result_array[0]['goodsID'],
                        'price' => $result_array[0]['salePrice'],
                        'exchange_price' => $goods['exchange_price'],
                        'mainPostID' => $result_array[0]['mainPostID'],
                        'product_code' => $result_array[0]['product_code'],
                        'spec' => $result_array[0]['spec'],
                        'img_link' => $domain_url . $result_array[0]['goodsMainPic'],
                        'selected' => 0,
                        'promotion_id' => $promotion['promotion_id']
                    );
                }
            }

            if ($condition < $promotion_json['condition_content']) {

                $order_promotion = array(
                    'is_meet' => 0,
                    'remark' => empty($promotion['remark']) ? $promotion['promotion_name'] : $promotion['remark'],
                    'type' => $promotion['promotion_type'],
                    'startTime' => $promotion['start_time'],
                    'endTime' => $promotion['end_time'],
                    'promotion_id' => $promotion['promotion_id'],
                    'condition' => $promotion_json['condition'],
                    'condition_content' => $promotion_json['condition_content'],
                    'spread' => round($promotion_json['condition_content'] - $condition, 2),
                    'gift' => $g,
                    'exchange' => $e,
                    'multiple' => 0
                );

            } else {

                if ($promotion['promotion_type'] == 8) {
                    $multiple = 1;
                    $subtract_money = $total_money * (1-$promotion_json['discount']);
                } else if ($promotion['promotion_type'] == 1) {
                    $subtract_money = $promotion_json['subtract_money'];
                } else {
                    $subtract_money = 0;
                }

                //赠卡券
                if ($promotion['promotion_type'] == 4) {
                    if (isset($promotion_json['coupon'])) {
                        foreach($promotion_json['coupon'] as $coupon) {
                            $coupon_data = CardCoupon::where(['card_id'=>$coupon['card_id']])->first();
                            if ($coupon_data) {
                                $coupon_data = $coupon_data->toArray();
                                $coupon_array[] = array(
                                    'promotionID' => $promotion['promotion_id'],
                                    'couponID' => $coupon['card_id'],
                                    'couponName' => $coupon_data[0]['card_name'],
                                    'couponNum' => $coupon['card_num'] * $multiple
                                );
                            }
                        }
                    }
                }

                $order_promotion = array(
                    'is_meet' => 1,
                    'remark' => empty($promotion['remark']) ? $promotion['promotion_name'] : $promotion['remark'],
                    'type' => $promotion['promotion_type'],
                    'startTime' => $promotion['start_time'],
                    'endTime' => $promotion['end_time'],
                    'promotion_id' => $promotion['promotion_id'],
                    'condition' => $promotion_json['condition'],
                    'condition_content' => $promotion_json['condition_content'],
                    'spread' => 0,
                    'subtractMoney' => $subtract_money,
                    'gift' => $g,
                    'exchange' => $e,
                    'coupon' => $coupon_array,
                    'is_repeat' => isset($promotion_json['is_repeat']) ? $promotion_json['is_repeat'] : 0,
                    'bill_status' => isset($promotion_json['bill_status']) ? $promotion_json['bill_status'] : null,
                    'activity_id' => isset($promotion_json['activity_id']) ? $promotion_json['activity_id'] : null,
                    'activity_name' => isset($promotion_json['activity_name']) ? $promotion_json['activity_name'] : null,
                    'multiple' => $multiple
                );
            }

            if ($goods_selector_type == 1) {
                if (isset($meet_array[$promotion['promotion_type']]))
                    continue;
                if ($order_promotion['is_meet']) {
                    $meet_array[$promotion['promotion_type']] = array(
                        'promotion_id' => $order_promotion['promotion_id'],
                        'condition' => $order_promotion['condition']
                    );
                }
            } else {
                $order_promotion['merge'] = $merge;
            }

            $return_data[] = $order_promotion;

        }
        
        return $return_data;

    }
    
    public static function calculate_rank( $arg_array ) {

//        $return = array(
//            'price' => round($arg_array['marketPrice'] * $arg_array['rate'], 2)
//        );
//
//        if ($arg_array['discount_flg'] == 1) {
//            $return['price'] = round($arg_array['salePrice'] * $arg_array['rate'], 2);
//        }
//
//        $return['salePoints'] = round($arg_array['salePoints'] * $arg_array['pointsRate']);
//
//        //查询商品等级价格及积分
//        $search_sql = 'SELECT * FROM goods_rank_relation WHERE product_code = ? AND rankID = ?';
//
//        if ($relation_data) {
//            $return['price'] = $relation_data[0]['price'];
//            $return['salePoints'] = $relation_data[0]['salePoints'];
//        }
//
//        return $return;

    }

    /**
     * 计算商品价格及检查商品促销
     * @param $args_data = array(
     *      'cust_rank' = array(), 会员等级数组
     *      'goods' => array()  购物车商品数组
     *      'rankID' => int 会员等级
     * )
     * @param bool|false $checkout
     * @return mixed
     */
    public static function calculate_goods_price($arg_array) {

        $goods_data = $arg_array['goods'];

        $args_data = array(
            'postID' => $goods_data['postID'],
            'salePrice' => $goods_data['salePrice'],
            'salePoints' => $goods_data['salePoints'],
            'product_code' => $goods_data['product_code'],
            'marketPrice' => $goods_data['marketPrice'],
            'goods_amount' => $goods_data['goods_amount'],
            'pcustID' => $arg_array['pcustID'],
            'mallareaID' => $arg_array['mallareaID'],
            'mallID' => $arg_array['mallID'],
            'platform' => $arg_array['platform'],
            'check' => $arg_array['check']
        );

        $promotion_array = self::goods($args_data);

        $goods_data['gift'] = null;

        if ( !empty($promotion_array['promotion'])) {
            foreach($promotion_array['promotion'] as $key=>$p_array) {
                if ($p_array['selected'] == 1) {
                    if ($p_array['promotion_type'] == 1){
                        $goods_data['price'] = $p_array['special_money'];
                        $goods_data['goods_amount'] = $p_array['goods_amount'];
                    } else if ($p_array['promotion_type'] == 2) {
                        $goods_data['gift'] = $p_array['gift'];
                    } else if ($p_array['promotion_type'] == 3) {
                        $goods_data['price'] = round($goods_data['price'] * $p_array['discount'], 2);
                    } else if ($p_array['promotion_type'] == 4) {
                        $goods_data['price'] = round(($goods_data['price'] * $goods_data['goods_amount'] - $p_array['half_money'])/$goods_data['goods_amount'], 2);
                    }
                    $goods_data['promotion_id'] = $p_array['promotion_id'];
                }
            }
            $goods_data['promotion'] = $promotion_array;
        } else {
            $goods_data['promotion'] = null;
        }

        return $goods_data;

    }

}
